package cn.net.vote.data.controller;

import cn.net.vote.data.domain.Page;
import cn.net.vote.data.domain.PageData;
import cn.net.vote.data.domain.ResponseBodyBean;
import cn.net.vote.data.service.IBusinessService;
import cn.net.vote.util.ConfigUtil;
import cn.net.vote.util.FileUpload;
import io.swagger.annotations.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【描 述】：<商户管理模块控制层>
 * 【表 名】：<数据库表名称>
 * 【环 境】：J2SE 1.8

 * @version  version 1.0
 * @since    2018年9月11日
 */
@Api(description = "商户管理", value = "/")
@RestController
@EnableAutoConfiguration
@RequestMapping(value="/business")
public class BusinessController extends BaseController{

    @Autowired
    private IBusinessService businessService;

    /*@ApiOperation(value = "查询所有商户", notes = "查询所有商户方法")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "page", dataType = "Page", required = true, value = "客户端传入JSON字符串", defaultValue = "")  })
    @ApiResponses({
            @ApiResponse(code=200,message="指示客服端的请求已经成功收到，解析，接受"),
            @ApiResponse(code=201,message="资源已被创建"),
            @ApiResponse(code=401,message="未授权"),
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=403,message="拒绝访问"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code=406,message="不是指定的数据类型"),
            @ApiResponse(code=500,message="服务器内部错误")
    })
    @RequestMapping(value="/findAllBusinesslistPage", method= RequestMethod.POST)
    public  @ResponseBody ResponseBodyBean findAllBusinesslistPage(@RequestBody Page page ) throws IOException {
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        ResponseBodyBean responseBodyBean = new ResponseBodyBean();
        PageData pdPageData = new PageData();
        //查询所有商户
        List<PageData> findAllBusiness = businessService.findAllBusinesslistPage(page);
        //查询所有参与商户数量
        Integer businessCount= businessService.findAllCount();
        pdPageData.put("list", findAllBusiness);
        pdPageData.put("businessCount", businessCount);
        pdPageData.put("page", page);
        status = HttpStatus.OK.value();
        responseBodyBean.setResult(pdPageData);
        response.setStatus(status);
        return responseBodyBean;
    }*/

    @ApiOperation(value = "查询所有商户-不分页", notes = "查询所有商户方法-不分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "pd", dataType = "PageData", required = true, value = "客户端传入JSON字符串", defaultValue = "")  })
    @ApiResponses({
            @ApiResponse(code=200,message="指示客服端的请求已经成功收到，解析，接受"),
            @ApiResponse(code=201,message="资源已被创建"),
            @ApiResponse(code=401,message="未授权"),
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=403,message="拒绝访问"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code=406,message="不是指定的数据类型"),
            @ApiResponse(code=500,message="服务器内部错误")
    })
    @RequestMapping(value="/findAllBusiness", method= RequestMethod.POST)
    public  @ResponseBody ResponseBodyBean findAllBusiness(@RequestBody PageData pd ) throws IOException {
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        ResponseBodyBean responseBodyBean = new ResponseBodyBean();
        PageData pdPageData = new PageData();
        //查询所有商户
        List<PageData> findAllBusiness = businessService.findAllBusiness(pd);
        //查询所有参与商户数量
        Integer businessCount= businessService.findAllCount();
        //查询当前投票总和
        Integer sumVote= businessService.getSumVote();
        for(PageData p :findAllBusiness) {
            String [] pic = p.getString("business_pic").split(",");
            List<PageData> picList = new ArrayList<PageData>() ;
            for(int i=0;i<pic.length;i++){
                picList.add(new PageData("picUrl",pic[i].toString()));
                p.put("picList" ,picList);
            }
        }
        pdPageData.put("list", findAllBusiness);
        pdPageData.put("businessCount", businessCount);
        pdPageData.put("sumVote", sumVote);
        pdPageData.put("pd", pd);
        status = HttpStatus.OK.value();
        responseBodyBean.setResult(pdPageData);
        response.setStatus(status);
        return responseBodyBean;
    }

    @ApiOperation(value = "查看商户详情", notes = "查看商户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "pd", dataType = "PageData", required = true, value = "客户端传入JSON字符串", defaultValue = "")  })
    @ApiResponses({
            @ApiResponse(code=200,message="指示客服端的请求已经成功收到，解析，接受"),
            @ApiResponse(code=201,message="资源已被创建"),
            @ApiResponse(code=401,message="未授权"),
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=403,message="拒绝访问"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code=406,message="不是指定的数据类型"),
            @ApiResponse(code=500,message="服务器内部错误")
    })
    @RequestMapping(value="/findBusinessOne", method= RequestMethod.POST)
    public  @ResponseBody ResponseBodyBean findBusinessOne(@RequestBody PageData pd ) throws IOException {
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        ResponseBodyBean responseBodyBean = new ResponseBodyBean();
        PageData pdPageData = new PageData();
        PageData findBusinessOne= businessService.findBusinessOne(pd);
        PageData pmData = businessService.voteRankingsOfBusiness(pd);

        //如果该商户不是排名第一的话查询该商户上一名
        if(!"1".equals(pmData.get("rownum").toString())){
            pdPageData.put("rownum",Integer.parseInt(pmData.get("rownum").toString())-1);
            PageData spmData = businessService.voteRankingsOfBusiness(pdPageData);
            //计算相差票数
            Integer espaceVote =  Integer.parseInt(spmData.get("numberOfVote").toString()) - Integer.parseInt(pmData.get("numberOfVote").toString());
            pdPageData.remove("rownum");
            pdPageData.put("nowPm", pmData.get("rownum").toString());
            pdPageData.put("espaceVote", espaceVote);
        }else{
            pdPageData.put("nowPm", "1");
            pdPageData.put("espaceVote", 0);
        }
        String [] pic = findBusinessOne.getString("business_pic").split(",");
        List<PageData> picList = new ArrayList<PageData>() ;
        for(int i=0;i<pic.length;i++){
            picList.add(new PageData("picUrl",pic[i].toString()));

        }
        findBusinessOne.put("picList" ,picList);
        pdPageData.put("list", findBusinessOne);
        status = HttpStatus.OK.value();
        responseBodyBean.setResult(pdPageData);
        response.setStatus(status);
        return responseBodyBean;
    }

    @ApiOperation(value = "投票计数", notes = "投票计数")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "pd", dataType = "PageData", required = true, value = "客户端传入JSON字符串", defaultValue = "")  })
    @ApiResponses({
            @ApiResponse(code=200,message="指示客服端的请求已经成功收到，解析，接受"),
            @ApiResponse(code=201,message="资源已被创建"),
            @ApiResponse(code=401,message="未授权"),
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=403,message="拒绝访问"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code=406,message="不是指定的数据类型"),
            @ApiResponse(code=500,message="服务器内部错误")
    })
    @RequestMapping(value="/businessVote", method= RequestMethod.POST)
    public  @ResponseBody ResponseBodyBean businessVote(@RequestBody PageData pd ) throws IOException {
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        ResponseBodyBean responseBodyBean = new ResponseBodyBean();
        PageData pdPageData = new PageData();
        //查询该商户原有票数并加1
        PageData findBusinessOne= businessService.findBusinessOne(pd);
        pd.put("numberOfVote",Integer.parseInt(findBusinessOne.get("numberOfVote").toString())+1);
        //更新票数
        Integer result= businessService.businessVote(pd);
        //查询当前投票总和
        Integer sumVote= businessService.getSumVote();
        pdPageData.put("result", result);
        pdPageData.put("sumVote", sumVote);
        pdPageData.put("pd", pd);
        status = HttpStatus.OK.value();
        responseBodyBean.setResult(pdPageData);
        response.setStatus(status);
        return responseBodyBean;
    }

    @ApiOperation(value = "商户票数排行", notes = "商户票数排行")
    @ApiImplicitParams({})
    @ApiResponses({
            @ApiResponse(code=200,message="指示客服端的请求已经成功收到，解析，接受"),
            @ApiResponse(code=201,message="资源已被创建"),
            @ApiResponse(code=401,message="未授权"),
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=403,message="拒绝访问"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code=406,message="不是指定的数据类型"),
            @ApiResponse(code=500,message="服务器内部错误")
    })
    @RequestMapping(value="/VoteRankings", method= RequestMethod.POST)
    public  @ResponseBody ResponseBodyBean VoteRankings() throws IOException {
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        ResponseBodyBean responseBodyBean = new ResponseBodyBean();
        PageData pdPageData = new PageData();
        List<PageData> VoteRankings= businessService.voteRankings();
        pdPageData.put("list", VoteRankings);
        status = HttpStatus.OK.value();
        responseBodyBean.setResult(pdPageData);
        response.setStatus(status);
        return responseBodyBean;
    }

    @ApiOperation(value = "上传图片", notes = "上传图片")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "files", dataType = "MultipartFile", required = true, value = "客户端上传文件", defaultValue = "")  })
    @ApiResponses({
            @ApiResponse(code=200,message="指示客服端的请求已经成功收到，解析，接受"),
            @ApiResponse(code=201,message="资源已被创建"),
            @ApiResponse(code=401,message="未授权"),
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=403,message="拒绝访问"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code=406,message="不是指定的数据类型"),
            @ApiResponse(code=500,message="服务器内部错误")
    })
    @RequestMapping(value="/uploadImages", method=RequestMethod.POST)
    public  @ResponseBody ResponseBodyBean uploadImages(@RequestBody MultipartFile[] files) throws IOException {
        //定义http返回状态码
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        ResponseBodyBean responseBodyBean = new ResponseBodyBean();
        PageData pdPageData = new PageData();
        StringBuffer jsonUrl = new StringBuffer();

        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                // 上传文件
                String url = ConfigUtil.getString("file.uploadFolder");
                String filename = FileUpload.fileUp(file,url,randomNum(15).toString());
                String httpUrl = ConfigUtil.getString("file.serverIp")+"/upload/" + filename;
                FileUpload.getHtmlPicture(httpUrl,ConfigUtil.getString("file.uploadFolder"),filename);
                jsonUrl.append(httpUrl + ",");
            }
        }
        jsonUrl.deleteCharAt(jsonUrl.length() - 1);
        pdPageData.put("jsonUrl", jsonUrl);
        status = HttpStatus.OK.value();
        responseBodyBean.setResult(pdPageData);
        response.setStatus(status);
        return responseBodyBean;
    }

    @ApiOperation(value = "新增商户", notes = "新增商户")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "pd", dataType = "PageData", required = true, value = "客户端传入JSON字符串", defaultValue = "")  })
    @ApiResponses({
            @ApiResponse(code=200,message="指示客服端的请求已经成功收到，解析，接受"),
            @ApiResponse(code=201,message="资源已被创建"),
            @ApiResponse(code=401,message="未授权"),
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=403,message="拒绝访问"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code=406,message="不是指定的数据类型"),
            @ApiResponse(code=500,message="服务器内部错误")
    })
    @RequestMapping(value="/addBusiness", method= RequestMethod.POST)
    public  @ResponseBody ResponseBodyBean addBusiness(@RequestBody PageData pd ) throws IOException {
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        ResponseBodyBean responseBodyBean = new ResponseBodyBean();
        PageData pdPageData = new PageData();
        Integer result= businessService.addBusiness(pd);
        pdPageData.put("result", result);
        pdPageData.put("pd", pd);
        status = HttpStatus.OK.value();
        responseBodyBean.setResult(pdPageData);
        response.setStatus(status);
        return responseBodyBean;
    }

    /**
     * 随机生产 factor 位的数字，最大不超过 19位，因为long的最大值为19位
     * @param factor
     * @return
     */ public static Long randomNum(int factor){
         return new Double((Math.random() + 1) * Math.pow(10, factor - 1)).longValue();
     }

}
